package com.blb.thread;

import java.util.ArrayList;
import java.util.List;

/**
 * 包子铺
 */
public class BaoziShop {

    //上限
    public static final int MAX_COUNT = 100;

    //包子缓冲区
    private List<Baozi> baozis = new ArrayList<>();

    /**
     * 做包子
     */
    public synchronized void makeBaozi(){
        //判断缓冲区是否满了
        if(baozis.size() == MAX_COUNT){
            //让线程等待
            System.out.println("包子铺满了!" + Thread.currentThread().getName() +"等待！");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            //通知生产者来生产
            this.notifyAll();
        }
        //创建包子存入缓冲区
        Baozi baozi = new Baozi(baozis.size());
        System.out.println(Thread.currentThread().getName()+"做了" + baozi);
        baozis.add(baozi);
    }

    /**
     * 卖包子
     */
    public synchronized void sellBaozi(){
        //判断缓冲区是否还有包子
        if(baozis.size() == 0){
            //让线程等待
            System.out.println("包子铺空了!" + Thread.currentThread().getName() +"等待！");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            //通知消费者来消费
            this.notifyAll();
        }
        //消费者消费包子
        if(baozis.size() > 0){
            Baozi baozi = baozis.remove(0);
            System.out.println(Thread.currentThread().getName() + "吃了" + baozi);
        }
    }
}
